package com.xing.controller;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.xing.Utils.Result;
import com.xing.config.JSONUtils;
import com.xing.dao.RoomDao;
import com.xing.dto.BarrageHistoryDTO;
import com.xing.entity.BarrageHistoryEntity;
import com.xing.entity.MessageEntity;
import com.xing.entity.RoomEntity;
import com.xing.service.BarrageHistoryService;
import com.xing.service.ViewHistryService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2024/1/12 17:08
 */
@Slf4j
@ServerEndpoint(value = "/web/websocket")
@Component
public class WebsocketServer {


    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static final CopyOnWriteArraySet<WebsocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    private String userId;
    private String roomId;

    private final ViewHistryService viewHistryService = SpringUtil.getBean(ViewHistryService.class);

    private final BarrageHistoryService barrageHistoryService = SpringUtil.getBean(BarrageHistoryService.class);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        //加入set中
        webSocketSet.add(this);
        //在线数加1
        addOnlineCount();
        log.info("有新用户：{}，加入房间{};当前连接数为{}", getUserId(), getRoomId(), getOnlineCount());
        getRoomId();
        //获取用户ID
        getUserId();
        /*添加浏览记录*/
        BarrageHistoryDTO dto = new BarrageHistoryDTO();
        dto.setSendId(userId);
        dto.setRoomId(roomId);
        dto.setContent("用户：" + getUserId() + "加入房间");
        dto.setMessageType(4);
        sendRoom(getRoomId(), dto);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从set中删除
        webSocketSet.remove(this);
        //在线数减1
        subOnlineCount();
        log.info("有一连接关闭={}！当前连接数为{}", getUserId(), getOnlineCount());
//        sendRoom(getRoomId(), new MessageEntity(userId, "离开房间", 1));
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println(message);
        //获取消息
        BarrageHistoryDTO dto = JSONUtils.jsonToObj(message, BarrageHistoryDTO.class);
        //判断消息类型
        assert dto != null;
        if (dto.getMessageType() == 0) {
            barrageHistoryService.save(JSONUtils.objParse(dto, BarrageHistoryEntity.class));
            sendRoom(getRoomId(), dto);
        } else if (dto.getMessageType() == 1) {
            sentOne(dto);
        } else if (dto.getMessageType() == 2) {
            sentOne(dto);
        } else if (dto.getMessageType() == 3) {
            sentOne(dto);
        } else if (dto.getMessageType() == 4) {
            sendRoom(getRoomId(), dto);
        }
        log.info("来自客户端的消息:{}", dto);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("websocket发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
            log.info("websocket发送消息成功：{}", message);
        } catch (IOException e) {
            log.error("websocket服务端发送消息异常");
            e.printStackTrace();
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebsocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebsocketServer.onlineCount--;
    }

    /**
     * 从url获取入参“userId”
     *
     * @return
     */
    private String getUserId() {
        String userId = getParameterMap().get("userId");

        //如没有传递userId，则关闭连接
        if (StringUtils.isEmpty(userId)) {
            sendMessage("userId不能为空");
            log.error("userId不能为空");
            throw new RuntimeException("userId不能为空");
        }
        this.userId = userId;
        return userId;
    }

    /**
     * 获取会议id
     *
     * @return
     */
    private String getRoomId() {
        String roomId = getParameterMap().get("roomId");

        //如没有传递userId，则关闭连接
        if (StringUtils.isEmpty(roomId)) {
            sendMessage("roomId不能为空");
            log.error("roomId不能为空");
            throw new RuntimeException("roomId不能为空");
        }
        this.roomId = roomId;
        return roomId;
    }


    private HashMap<String, String> getParameterMap() {
        HashMap<String, String> map = new HashMap<>();

        String queryString = session.getQueryString();
        if (StringUtils.isEmpty(queryString)) {
            return map;
        }

        String[] split = queryString.split("&");
        for (String s : split) {
            if (s.contains("=")) {
                String[] strings = s.split("=");
                map.put(strings[0], strings[1]);
            }
        }
        return map;
    }

    public boolean user(String userId) {
        for (WebsocketServer server : webSocketSet) {
            System.out.println(server.userId);
            if (server.userId.equals(userId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 广播消息
     */
    @Async
    public void sendAll(String message) {
        BarrageHistoryDTO dto = new BarrageHistoryDTO();
        dto.setContent(message);
        for (WebsocketServer server : webSocketSet) {
            server.sendMessage(JSONUtils.objToJson(dto));
        }
    }

    /**
     * 房间内广播
     *
     * @param roomId
     */
    @Async
    public void sendRoom(String roomId, BarrageHistoryDTO dto) {
        for (WebsocketServer server : webSocketSet) {
            boolean equals = server.roomId.equals(roomId);
            boolean equals1 = this.userId.equals(server.userId);
            log.info("遍历：this={},to={}", this.userId, server.userId);
            if (equals && (!equals1)) {
                server.sendMessage(JSONUtils.objToJson(dto));
            }
        }
    }

    /**
     * 对话模式
     *
     * @param dto
     */
    @Async
    public void












    sentOne(BarrageHistoryDTO dto) {
        assert dto != null;
        boolean user = user(dto.getReceivedId().toString());
        if (!user) {
            log.info("用户{}不在线", dto.getReceivedId());
            sendMessage(JSONUtils.objToJson(new Result().err(305, "对方不在线")));
        } else {
            for (WebsocketServer websocketServer : webSocketSet) {
                if (websocketServer.userId.equals(dto.getReceivedId())) {
                    websocketServer.sendMessage(JSONUtils.objToJson(dto));
                }
            }
        }
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }
}
